﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Compression;
using System.IO;
using System.Net;
using LGPSDataGen.Generators;
using System.Data.SqlClient;

namespace LGPSDataGen
{
    public partial class GenerationForm : Form
    {
        public GenerationForm()
        {
            InitializeComponent();
        }

        private void PJMButton_Click(object sender, EventArgs e)
        {
            Generator pjm = new PJMGenerator(dateTimePicker1.Value);
            pjm.CradleToGrave();
        }

        //Thread to do work for all days in the year
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            DateTime d = new DateTime(dateTimePicker1.Value.Year, 1, 1);
            int endDate;
            //Check if this is 2011 because there is a hard stop in PJM Data
            //at the end of June.
            if (d.Year == 2011)
            {
                endDate = 182;
            }
            else
            {
                endDate = 365;
            }

            while (d.DayOfYear < endDate)
            {
                List<IGenerator> Generators = new List<IGenerator>();
                Generator gen = new PJMGenerator(d);
                Generators.Add(gen);
                gen = new TemperatureGenerator(d);
                Generators.Add(gen);
                gen = new HumidityGenerator(d);
                Generators.Add(gen);
                gen = new WindGenerator(d);
                Generators.Add(gen);
                gen = new FlyersGenerator(d);
                Generators.Add(gen);
                gen = new EaglesGenerator(d);
                Generators.Add(gen);
                gen = new PhilliesGenerator(d);
                Generators.Add(gen);
                gen = new SevenSixersGenerator(d);
                Generators.Add(gen);
                gen = new StockGenerator(d);
                Generators.Add(gen);
                gen = new GasGenerator(d);
                Generators.Add(gen);

                foreach (Generator generator in Generators)
                {
                    generator.CradleToGrave();
                }

                WriteDataToDB(d);
                d = d.AddDays(1);
            }
        }

        //This method was originally introduced to write the data to the database
        //Instead this was used to create the CSV files to replace the DB
        //Once the DB was re-introduced, this method handled both to allow
        //the NN decide which to use
        private void WriteDataToDB(DateTime d)
        {
            string time_stamp = d.Year + "_" + d.Month + "_" + d.Day;

            string[] t = File.ReadAllLines(@"PJM-" + time_stamp + ".csv");
            string[] t2 = File.ReadAllLines(@"Wind-" + time_stamp + ".csv");
            string[] t3 = File.ReadAllLines(@"Temp-" + time_stamp + ".csv");
            string[] t4 = File.ReadAllLines(@"Humidity-" + time_stamp + ".csv");
            string[] t5 = null;
            string[] t6 = null;
            string[] t7 = null;
            string[] t8 = null;
            if (d.Year == 2011) //Sports are unavailable before 2011 because it would require a different generator
            {
                t5 = File.ReadAllLines(@"Eagles-" + time_stamp + ".csv");
                t6 = File.ReadAllLines(@"Flyers-" + time_stamp + ".csv");
                t7 = File.ReadAllLines(@"76ers-" + time_stamp + ".csv");
                t8 = File.ReadAllLines(@"Phillies-" + time_stamp + ".csv");
            }

            string[] t9 = File.ReadAllLines(@"Stock3-" + time_stamp + ".csv");
            string[] t10 = File.ReadAllLines(@"Gas2-" + time_stamp + ".csv");
            List<string> output = new List<string>();

            //Store the data into the database
            SqlConnection thisConnection = new SqlConnection(connString.Text);
            thisConnection.Open();
            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = thisConnection;

            try
            {
                myCommand.CommandText = String.Format("INSERT INTO PowerRegion VALUES(1, 'PECO' ) ");
                myCommand.ExecuteNonQuery();
            }
            catch (Exception)
            { }

            try
            {
                for (int i = 0; i < t.Count(); i++)
                {
                    int SportsCount = 0;
                    if (d.Year == 2011)
                    {
                        SportsCount = SportsCount + Int32.Parse(t5[i].Split(',')[1]);
                        SportsCount = SportsCount + Int32.Parse(t6[i].Split(',')[1]);
                        SportsCount = SportsCount + Int32.Parse(t7[i].Split(',')[1]);
                        SportsCount = SportsCount + Int32.Parse(t8[i].Split(',')[1]);
                    }
                    double percent = SportsCount;

                    string xys = t[i] + ";" + t2[i].Split(',')[1] + ";" + t3[i].Split(',')[1] + ";" + t4[i].Split(',')[1] + ";" + percent + ";" + t9[i].Split(',')[1];
                    output.Add(xys);

                    DateTime hour = new DateTime(d.Year, d.Month, d.Day);

                    hour = hour.AddHours(i);

                    myCommand.CommandText = String.Format("INSERT INTO Date VALUES('{0}', {1}, {2}, {3})", hour.ToString(), DateUtility.DayToInt(hour), DateUtility.IsHoliday(hour), DateUtility.WeekEndFlag(hour));
                    myCommand.ExecuteNonQuery();
                    myCommand.CommandText = String.Format("INSERT INTO PowerLoad VALUES ('{0}', 1, {1})", hour.ToString(), t[i].Split(',')[1]);
                    myCommand.ExecuteNonQuery();
                    myCommand.CommandText = String.Format("INSERT INTO Weather VALUES ('{0}', 1, {1}, {2}, {3})", hour.ToString(), t4[i].Split(',')[1], t3[i].Split(',')[1], t2[i].Split(',')[1]);
                    myCommand.ExecuteNonQuery();
                    myCommand.CommandText = String.Format("INSERT INTO NonTraditionalData VALUES ('{0}', 1, 0, {1}, {2}, {3})", hour.ToString(), percent, t9[i].Split(',')[1], t10[i].Split(',')[1]);
                    myCommand.ExecuteNonQuery();

                }
                File.WriteAllLines(@"All" + ".txt", output.ToArray());
                File.WriteAllLines(@"All-" + time_stamp + ".txt", output.ToArray());
                thisConnection.Close();
            }
            catch (Exception ex)
            {
                thisConnection.Close();
                MessageBox.Show("Error writing to DB");
            }
        }

        //Reset the form when processing is done
        private void thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Style = ProgressBarStyle.Blocks;
            this.Cursor = Cursors.Default;
        }

        private void ButtonAll_Click(object sender, EventArgs e)
        {
            BackgroundWorker thread = new BackgroundWorker();
            thread.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
            thread.RunWorkerAsync();
            this.Cursor = Cursors.WaitCursor;
            progressBar1.Style = ProgressBarStyle.Marquee;
        }

        private void TemperatureButton_Click(object sender, EventArgs e)
        {
            Generator temperature = new TemperatureGenerator(dateTimePicker1.Value);
            temperature.CradleToGrave();
        }

        private void humidityButton_Click(object sender, EventArgs e)
        {
            Generator humidity = new HumidityGenerator(dateTimePicker1.Value);
            humidity.CradleToGrave();
        }

        private void windButton_Click(object sender, EventArgs e)
        {
            Generator wind = new WindGenerator(dateTimePicker1.Value);
            wind.CradleToGrave();
        }

        protected DateTime theDate
        {
            get
            {
                if (mTheDate == null)
                {
                    mTheDate = dateTimePicker1.Value;
                }
                return mTheDate;
            }
        }

        private DateTime mTheDate;

        private void eaglesButton_Click(object sender, EventArgs e)
        {
            Generator eagles = new EaglesGenerator(dateTimePicker1.Value);
            eagles.CradleToGrave();
        }

        private void SeventySixButton_Click(object sender, EventArgs e)
        {
            Generator p76ers = new SevenSixersGenerator(dateTimePicker1.Value);
            p76ers.CradleToGrave();
        }

        private void PhilliesButton_Click(object sender, EventArgs e)
        {
            Generator Philies = new PhilliesGenerator(dateTimePicker1.Value);
            Philies.CradleToGrave();
        }

        private void FlyersButton_Click(object sender, EventArgs e)
        {
            Generator Flyers = new FlyersGenerator(dateTimePicker1.Value);
            Flyers.CradleToGrave();
        }

        private void StockButton_Click(object sender, EventArgs e)
        {
            Generator Stock = new StockGenerator(dateTimePicker1.Value);
            Stock.CradleToGrave();
        }

        private void GenerationForm_Load(object sender, EventArgs e)
        {
            connString.Text = Properties.Settings.Default.ConnectionString;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void connString_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Generator Gas = new GasGenerator(dateTimePicker1.Value);
            Gas.CradleToGrave();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Value is: " + DateUtility.WeekEndFlag(dateTimePicker1.Value));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Value is: " + DateUtility.IsHoliday(dateTimePicker1.Value));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            BackgroundWorker thread = new BackgroundWorker();
            thread.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWorkForADay);
            thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
            thread.RunWorkerAsync();
            this.Cursor = Cursors.WaitCursor;
            progressBar1.Style = ProgressBarStyle.Marquee;
        }

        //Same as the work for a year but for the day
        private void backgroundWorker1_DoWorkForADay(object sender, DoWorkEventArgs e)
        {
            DateTime d = dateTimePicker1.Value;
            List<IGenerator> Generators = new List<IGenerator>();
            Generator gen = new PJMGenerator(d);
            Generators.Add(gen);
            gen = new TemperatureGenerator(d);
            Generators.Add(gen);
            gen = new HumidityGenerator(d);
            Generators.Add(gen);
            gen = new WindGenerator(d);
            Generators.Add(gen);
            gen = new FlyersGenerator(d);
            Generators.Add(gen);
            gen = new EaglesGenerator(d);
            Generators.Add(gen);
            gen = new PhilliesGenerator(d);
            Generators.Add(gen);
            gen = new SevenSixersGenerator(d);
            Generators.Add(gen);
            gen = new StockGenerator(d);
            Generators.Add(gen);
            gen = new GasGenerator(d);
            Generators.Add(gen);

            foreach (Generator generator in Generators)
            {
                generator.CradleToGrave();
            }

            WriteDataToDB(d);
        }
    }
}
